<?php
class Shop_Model_Base extends Apm_Model_Base{

	/**
     * sql文を発行し、データベースからデータを取得（単数）
     *
     * @param $params
     * @return 取得結果
     */
    public function getData($params)
    {
        $db_params = array();
        $sql = $this->generateSql($params, $db_params);

        return $this->dbGetData($sql, $db_params);
    }

    /**
     * sql文を発行し、データベースからデータを取得（複数）
     * @param $params
     * @return 取得結果
     */
	public function getList($params)
    {
        $db_params = array();
        $sql = $this->generateSql($params, $db_params);

        return $this->dbGetList($sql, $db_params);
    }

    /**
     * sql文を発行し、データベースからデータを取得（ページング用）
     * @param $params
     * @return 取得結果
     */
    public function getPagingList($params, $sort, $start, $count)
    {
        $db_params = array();

        $sql = '';
        $sql .= ' SELECT * FROM (';
        $sql .= ' SELECT ROWNUM AS RN, TBL.* FROM (';
        $sql .= $this->generateSql($params, $db_params);
        $sql .= ' ) TBL ';
        $sql .= ' ) ';
        if ($count > 0){
            $sql .= sprintf(' WHERE RN BETWEEN %d AND %d', $start, $start + $count - 1);
        }

        return $this->dbGetList($sql, $db_params);
    }

    /**
     * 件数取得
     * @param $params
     * @return 件数
     */
    public function getCount($params)
    {
    	$db_params = array();
        $sql = '';
        $sql .= 'SELECT COUNT(*) AS TOTAL_COUNT FROM (';
        $sql .= $this->generateSql($params, $db_params);
        $sql .= ') tbl';

        $data = $this->dbGetData($sql, $db_params);
        return (int)$data['TOTAL_COUNT'];
    }

	/*
	 * ウェブコーリング変換
	 */
    public function convertWebcallingTel($data)
    {
	    if (Apm_Bukkenitems::isWebCalling($data))
		{
            $data['IS_WEBCALLING'] = true;
            $data['TEL_01'] = Apm_Config_Shop::FREE_CALLING_NO;
            $data['TEL_02'] = $data['M05_TENPO_TEL01'];
			// 無料アイコン表示
			$data['hasFreeTel'] = true;
		}
		else
		{
			$data['IS_WEBCALLING'] = false;

			// 無料電話番号
			$tel01 = $data['M05_TENPO_TEL01'];
			// 公開電話番号
			$tel02 = $data['M05_TENPO_TEL02'];

			// 無料電話番号(表示用)
			$data['TEL_01'] = '';
			// 公開電話番号(表示用)
			$data['TEL_02'] = '';

			// 無料電話番号に番号がある場合
			if (!empty($tel01))
			{
				if (substr($tel01, 0, 4) == '0120')
				{
					$data['TEL_01'] = $tel01;
				}
				else
				{
					$data['TEL_02'] = $tel01;
				}
			}
            // 通常電話番号に番号がある場合
			if (!empty($tel02))
			{
				if ($data['TEL_01'] == '' && substr($tel02, 0, 4) == '0120')
				{
					$data['TEL_01'] = $tel02;
				}
				elseif ($data['TEL_02'] == '' && substr($tel02, 0, 4) != '0120')
				{
					$data['TEL_02'] = $tel02;
				}
			}

			if ($data['TEL_01'] == '')
			{
				// 無料アイコン非表示
				$data['hasFreeTel'] = false;

				$data['TEL_01'] = $data['TEL_02'];
				$data['TEL_02'] = '-';

				if ($data['TEL_01'] == '')
				{
					$data['TEL_01'] = '-';
				}
			}
			else
			{
				// 無料アイコン表示
				$data['hasFreeTel'] = true;

				if ($data['TEL_02'] == '') $data['TEL_02'] = '-';
			}
		}

		return $data;
    }

	/*
	 * Webcalling接続番号変換
	 */
	public function convertWebcallingNo($data)
	{
		$subNo = '';
		$connectionNo = '';

		if ($_COOKIE['webcalling_type'] != '')
		{
			// WebCalling(type)用Cookieが設定されている場合
			$subNo = $_COOKIE['webcalling_type'];
			$connectionNo = Apm_ShopUtil::getFreeCallingNo($data, $subNo);
		}
		if (empty($webCallingNo)) {
			// デフォルトNo取得
			$subNo = Apm_Config_Shop::FREE_CONNECTION_NO_6;
			$connectionNo = Apm_ShopUtil::getFreeCallingNo($data, $subNo);
		}

		return trim($connectionNo);
	}

	/*
	 * 無料電話番号 変換
	 */
	public function convertFreeCalling($data)
	{
		// 無料電話チェック
		$callData = Apm_ShopUtil::getCallingData($data, Apm_Config_Shop::FREE_CONNECTION_NO_6);

		// 無料電話使用の場合、接続番号を取得
		if ($callData['IS_FREE_CALL']) {
			$callData['CONNECTION_NO'] = $this->convertWebcallingNo($data);
		}

		return $callData;
	}

    /*
     * 定休日変換
     */
    public function convertTeikyuubi($data)
    {
    	$teikyubi = $data['M05_TEIKYUUBI'];
    	$teikyubiBikou = $data['M05_TEIKYUUBI_BIKOU'];
    	$teikyubiName = '';

		if ($teikyubi == '0000000' && $teikyubiBikou == '')
		{
			$teikyubiName = '-';
		}
		else
		{
    		$array = array();

			if (substr($teikyubi, 0, 1) == '1') $array[] = '月曜日';
			if (substr($teikyubi, 1, 1) == '1') $array[] = '火曜日';
			if (substr($teikyubi, 2, 1) == '1') $array[] = '水曜日';
			if (substr($teikyubi, 3, 1) == '1') $array[] = '木曜日';
			if (substr($teikyubi, 4, 1) == '1') $array[] = '金曜日';
			if (substr($teikyubi, 5, 1) == '1') $array[] = '土曜日';
			if (substr($teikyubi, 6, 1) == '1') $array[] = '日曜日';
			if ($teikyubiBikou != '')           $array[] = $teikyubiBikou;
			$teikyubiName = join(" ", $array);
		}
		return $teikyubiName;
    }

    /*
     * 営業時間変換
     */
    public function convertEigyouZikan($data)
    {
		$eigyouOpenH = $data['M05_EIGYOU_ZIKAN_OPEN_H'];
		$eigyouOpenM = $data['M05_EIGYOU_ZIKAN_OPEN_M'];
		$eigyouCloseH = $data['M05_EIGYOU_ZIKAN_CLOSE_H'];
		$eigyouCloseM = $data['M05_EIGYOU_ZIKAN_CLOSE_M'];
		$eigyouBikou = $data['M05_EIGYOU_ZIKAN_BIKOU'];
		$eigyouZikan = '';

		if (!($eigyouOpenH =='' && $eigyouOpenM == '' && $eigyouCloseH == '' && $eigyouCloseM == '' && $eigyouBikou == ''))
		{
			if (is_null($eigyouOpenH))$eigyouOpenH == '--';
			if (is_null($eigyouOpenM))$eigyouOpenM == '--';
			if (is_null($eigyouCloseH))$eigyouCloseH == '--';
			if (is_null($eigyouCloseM))$eigyouCloseM == '--';

			$eigyouZikan = substr('00'.$eigyouOpenH, -2).':'.substr('00'.$eigyouOpenM, -2).'～'.substr('00'.$eigyouCloseH, -2).':'.substr('00'.$eigyouCloseM, -2).'　'.$eigyouBikou;
		}
		return $eigyouZikan;
    }

	/**
	 * WHERE句 IN 構文の作成
	 *
	 */
	protected function generateWhereIn($column, $params, &$db_params, $flag=true)
	{
		$sql = '';
		if (empty($column) || empty($params)) return '';

		if (!is_array($params)) {
			// 配列でない場合
			$sql .= ($flag) ? ' = ' : ' != ';
			$sql .= ':' . $column . ' ';
			$db_params[$column] = $params;
		} elseif (count($params) == 1) {
			// 配列が１つの場合
			$sql .= ($flag) ? ' = ' : ' != ';
			$sql .= ':' . $column . ' ';
			$db_params[$column] = array_shift($params);	// 先頭を取り出す
		} else {
			// 配列の場合
			$sql .= ($flag) ? ' in ' : ' not in ';
			$sql .= '( ';
			$i = 0;
			foreach ($params as $prm) {
				if ($i != 0) $sql .= ', ';
				$i++;
				$sql .= ":{$column}_{$i} ";
				$db_params["{$column}_{$i}"] = $prm;
			}
			$sql .= ')';
		}

		return $sql;
	}

	/**
     * サービス内容から検索する際の条件を生成
     * @param $params
     * @return sql条件文
     */
	protected function generateCondService($params)
	{
    	$sql = '';

        if (array_key_exists('tokucho01', $params) && $params['tokucho01'] == '1') $sql .= " AND M05_TOKUCHO01 = 1 ";
        if (array_key_exists('tokucho02', $params) && $params['tokucho02'] == '1') $sql .= " AND M05_TOKUCHO02 = 1 ";
        if (array_key_exists('tokucho03', $params) && $params['tokucho03'] == '1') $sql .= " AND M05_TOKUCHO03 = 1 ";
        if (array_key_exists('tokucho04', $params) && $params['tokucho04'] == '1') $sql .= " AND M05_TOKUCHO04 = 1 ";
        if (array_key_exists('tokucho05', $params) && $params['tokucho05'] == '1') $sql .= " AND M05_TOKUCHO05 = 1 ";
        if (array_key_exists('tokucho06', $params) && $params['tokucho06'] == '1') $sql .= " AND M05_TOKUCHO06 = 1 ";
        if (array_key_exists('tokucho07', $params) && $params['tokucho07'] == '1') $sql .= " AND M05_TOKUCHO07 = 1 ";
        if (array_key_exists('tokucho08', $params) && $params['tokucho08'] == '1') $sql .= " AND M05_TOKUCHO08 = 1 ";
        if (array_key_exists('tokucho09', $params) && $params['tokucho09'] == '1') $sql .= " AND M05_TOKUCHO09 = 1 ";
        if (array_key_exists('tokucho10', $params) && $params['tokucho10'] == '1') $sql .= " AND M05_TOKUCHO10 = 1 ";
        if (array_key_exists('tokucho11', $params) && $params['tokucho11'] == '1') $sql .= " AND M05_TOKUCHO11 = 1 ";
        if (array_key_exists('tokucho12', $params) && $params['tokucho12'] == '1') $sql .= " AND M05_TOKUCHO12 = 1 ";
        if (array_key_exists('tokucho13', $params) && $params['tokucho13'] == '1') $sql .= " AND M05_TOKUCHO13 = 1 ";
        if (array_key_exists('tokucho14', $params) && $params['tokucho14'] == '1') $sql .= " AND M05_TOKUCHO14 = 1 ";
        if (array_key_exists('tokucho15', $params) && $params['tokucho15'] == '1') $sql .= " AND M05_TOKUCHO15 = 1 ";
        if (array_key_exists('tokucho16', $params) && $params['tokucho16'] == '1') $sql .= " AND M05_TOKUCHO16 = 1 ";

        return $sql;
	}

	/**
     * フリーワードから検索する際の条件を生成
     * @param $params
     * @return sql条件文
     */
	protected function generateCondFreeWord($params)
	{
    	$sql = '';
		$strFreeWd = $params['FreeWd'];
		$strFreeWdLike = strtoupper(mb_convert_kana($strFreeWd,'as',Apm_Config_Common::PHP_CHAR_SET));

        $sql .= " AND ( M05_TENPO_NAME LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_TENPO_NAME)) LIKE '%".$strFreeWdLike."%' ";
        $sql .= " OR M05_HOUZINMEI LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_HOUZINMEI)) LIKE '%".$strFreeWdLike."%' ";
        $sql .= " OR M05_JYUUSHO_TEXT LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_JYUUSHO_TEXT)) LIKE '%".$strFreeWdLike."%' ";
        $sql .= " OR M05_TENPO_BANCHI LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_TENPO_BANCHI)) LIKE '%".$strFreeWdLike."%' ";
        $sql .= " OR M05_TENPO_JYUUSHO_BIKOU LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_TENPO_JYUUSHO_BIKOU)) LIKE '%".$strFreeWdLike."%' ";
        $sql .= " OR M05_TENPO_TEL01 LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_TENPO_TEL01)) LIKE '%".$strFreeWdLike."%' ";
        $sql .= " OR M05_TENPO_FAX LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_TENPO_FAX)) LIKE '%".$strFreeWdLike."%' ";
        $sql .= " OR M05_TENPO_URL LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_TENPO_URL)) LIKE '%".$strFreeWdLike."%' ";
        $sql .= " OR M05_TENPO_MAIL LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_TENPO_MAIL)) LIKE '%".$strFreeWdLike."%' ";
        $sql .= " OR M05_KOUTSUU_TEXT01 LIKE '%{$strFreeWd}%' ";
        $sql .= " OR UPPER(to_single_byte(M05_KOUTSUU_TEXT01)) LIKE '%".$strFreeWdLike."%' ) ";

        return $sql;
	}

	/**
	 * ダミー店舗除外条件を生成
	 * @param $column
	 * @param &$db_params
	 * @return sql条件文
	 */
	protected function generateNotinDummyShop($column, &$db_params)
	{
		if (empty($column)) return '';

		// IN文の生成
		$sql = $this->generateWhereIn('dummyShopCd', array_filter(Apm_Config_Shop::$DUMMY_SHOP_LIST), $db_params, false);
		// NOT IN へ変換
		if (!empty($sql)) $sql = ' AND ' . $column . $sql;
		return $sql;
	}

    /**
     * リクエストパラメータ変換
     * @param $requestData
     */
	public function convertRequestParam(&$requestData)
	{
		$checked = "checked='checked'";

		// 都道府県
        if (empty($requestData['PrefCd']) || count($requestData['PrefCd']) == 0)
        {
        	$requestData['isSelectedPref'] = false;
        }
        else
        {
        	$requestData['isSelectedPref'] = true;
        	$requestData['PrefNameList'] = array();

        	foreach ($requestData['PrefCd'] as $PrefCd)
        	{
	        	$keyName = "PrefCd{$PrefCd}checked";
        		$requestData[$keyName] = $checked;

        		$requestData['PrefNameList'][] = Apm_Config_Shop::$PREF_LIST["$PrefCd"];
        	}
        	$requestData['PrefNames'] = join("<br/>", $requestData['PrefNameList']);
        }

        // 市区町村
        if (empty($requestData['CityCd']) || count($requestData['CityCd']) == 0)
        {
        	$requestData['isSelectedCity'] = false;
        }
        else
        {
        	$requestData['isSelectedCity'] = true;
        	$requestData['CityNameList'] = array();
        	$sqlList = array();
        	$cond = '';

        	// 市区町村名取得
        	foreach ($requestData['CityCd'] as $PrefCityCd)
        	{
		        $PrefCd = substr($PrefCityCd, 0, 2);
		        $CityCd = substr($PrefCityCd, 2);
		        $sqlList[] = " (M05_TENPO_TODOUFUKEN_CD = '{$PrefCd}' AND M05_TENPO_SHIKUCHOUSON_CD = '{$CityCd}') ";
        	}
        	if (count($sqlList) > 0)
        	{
	        	$cond = ' WHERE (' . join(" OR ", $sqlList) . ') ';
	        	$sql =  " SELECT M05_TENPO_TODOUFUKEN_CD, M05_TENPO_SHIKUCHOUSON_CD, M05_TENPO_SHIKUCHOUSON FROM M05TENPO_INFO {$cond} ";
	        	$sql .= " GROUP BY M05_TENPO_TODOUFUKEN_CD, M05_TENPO_SHIKUCHOUSON_CD, M05_TENPO_SHIKUCHOUSON ";
	        	$sql .= " ORDER BY M05_TENPO_TODOUFUKEN_CD ASC, M05_TENPO_SHIKUCHOUSON_CD ASC";

	        	foreach ($this->dbGetList($sql) as $shop)
	        	{
	        		$requestData['CityNameList'][] = $shop['M05_TENPO_SHIKUCHOUSON'];
	        	}
	       		$requestData['CityNames'] = join("<br/>", $requestData['CityNameList']);
        	}
        }

        // 沿線
        if (empty($requestData['RailCd']) || count($requestData['RailCd']) == 0)
        {
        	$requestData['isSelectedRail'] = false;
        }
        else
        {
        	$requestData['isSelectedRail'] = true;
        	$requestData['RailNameList'] = array();
        	$RailCdList = array();

			// 沿線名取得
        	foreach ($requestData['RailCd'] as $PrefRailCd)
        	{
        		$RailCd = '';

	        	if (strlen($PrefRailCd) == 4)
	        	{
	        		$RailCd = $PrefRailCd;
	        	}
	        	else
	        	{
			        $RailCd = substr($PrefRailCd, 2);
	        	}
        		$RailCdList[$RailCd] = '';
        	}

        	if (count($RailCdList) > 0)
        	{
        		$keys = array_keys($RailCdList);

        		$cond = " WHERE M02_ENSEN_CD IN ('" . join("','", $keys) . "') ";
	        	$sql = "SELECT M02_ENSEN_CD, M02_ENSEN_NAME FROM M02ENSEN {$cond} GROUP BY M02_ENSEN_CD, M02_ENSEN_NAME";

	        	foreach ($this->dbGetList($sql) as $rail)
	        	{
	        		$RailCdList[$rail['M02_ENSEN_CD']] = $rail['M02_ENSEN_NAME'];
	        	}

	        	$requestData['RailCd'] = $keys;
	        	$requestData['RailNames'] = join("<br/>", array_values($RailCdList));
        	}
        }

        // サービス検索
        for ($index = 2; $index <= 16; $index++)
        {
        	$no = sprintf("%02d", $index);
        	$key = "tokucho{$no}";

        	if (!empty($requestData[$key]) && $requestData[$key] == '1')
        	{
        		$keyName = "{$key}checked";
        		$requestData[$keyName] = $checked;
        	}
        }
	}
}
?>
